import React from 'react'

// 属性的类型
type Props = {
  onAddTodo: (text: string) => void
}

// 状态的类型
type State = {
  text: string
}

class TodoAdd extends React.Component<Props, State> {
  state: State = {
    text: ''
  }

  onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({
      text: e.target.value
    })
  }

  onAdd = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.code === 'Enter') {
      const { text } = this.state
      if (text.trim().length === 0) return

      this.props.onAddTodo(text)

      // 清空之前输入的内容
      this.setState({
        text: ''
      })
    }
  }

  render () {
    return (
      <header className='header'>
        <h1>todos</h1>
        <input
          className='new-todo'
          placeholder='What needs to be done?'
          autoFocus
          value={this.state.text}
          onChange={this.onChange}
          onKeyDown={this.onAdd}
        />
      </header>
    )
  }
}

export default TodoAdd
